import sys
import os
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QPushButton, QLabel, QScrollArea, QFileDialog, QDialog, 
                            QLineEdit, QComboBox, QCheckBox, QGroupBox, QMessageBox)
from PyQt5.QtCore import Qt, QRect, QSize, QThread, pyqtSignal, QSettings
from PyQt5.QtGui import QPixmap, QIcon, QFont, QColor, QPainter, QPen
import keyboard
import win32clipboard
from io import BytesIO
import cv2
import numpy as np
from PIL import ImageGrab, Image, ImageDraw, ImageFont
import threading
import pystray
from pystray import MenuItem as item
from PIL import Image as PILImage

class ScreenRecorder(QThread):
    finished = pyqtSignal(str)
    
    def __init__(self):
        super().__init__()
        self.recording = False
        self.output_path = os.path.join(os.path.expanduser("~"), "Desktop")
        
    def run(self):
        self.recording = True
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = os.path.join(self.output_path, f"recording_{timestamp}.avi")
        
        # 设置视频编码
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        fps = 20
        screen_size = (1920, 1080)  # 默认分辨率，实际会动态获取
        out = cv2.VideoWriter(filename, fourcc, fps, screen_size)
        
        while self.recording:
            img = ImageGrab.grab()
            frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
            out.write(frame)
            
        out.release()
        self.finished.emit(filename)

class SettingsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("设置")
        self.setFixedSize(500, 400)
        self.setStyleSheet("""
            QDialog {
                background-color: #2d2d2d;
                color: #ffffff;
                font-family: 'Microsoft YaHei';
            }
            QGroupBox {
                border: 1px solid #444;
                border-radius: 5px;
                margin-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 3px;
            }
            QLineEdit, QComboBox {
                background-color: #3d3d3d;
                border: 1px solid #444;
                border-radius: 3px;
                padding: 5px;
                color: #ffffff;
            }
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 5px;
                padding: 8px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        
        self.initUI()
        self.load_settings()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 快捷键设置
        hotkey_group = QGroupBox("快捷键设置")
        hotkey_layout = QVBoxLayout()
        
        self.screenshot_hotkey = QLineEdit()
        self.recording_hotkey = QLineEdit()
        self.stop_recording_hotkey = QLineEdit()
        
        hotkey_layout.addWidget(QLabel("截图快捷键:"))
        hotkey_layout.addWidget(self.screenshot_hotkey)
        hotkey_layout.addWidget(QLabel("开始录屏快捷键:"))
        hotkey_layout.addWidget(self.recording_hotkey)
        hotkey_layout.addWidget(QLabel("停止录屏快捷键:"))
        hotkey_layout.addWidget(self.stop_recording_hotkey)
        
        hotkey_group.setLayout(hotkey_layout)
        
        # 存储设置
        storage_group = QGroupBox("存储设置")
        storage_layout = QVBoxLayout()
        
        self.storage_path = QLineEdit()
        self.browse_btn = QPushButton("浏览...")
        self.browse_btn.clicked.connect(self.browse_storage_path)
        
        path_layout = QHBoxLayout()
        path_layout.addWidget(self.storage_path)
        path_layout.addWidget(self.browse_btn)
        
        storage_layout.addWidget(QLabel("文件保存路径:"))
        storage_layout.addLayout(path_layout)
        storage_group.setLayout(storage_layout)
        
        # 其他设置
        other_group = QGroupBox("其他设置")
        other_layout = QVBoxLayout()
        
        self.watermark_text = QLineEdit()
        self.auto_start = QCheckBox("开机自启动")
        self.auto_update = QCheckBox("自动更新")
        
        other_layout.addWidget(QLabel("水印文字:"))
        other_layout.addWidget(self.watermark_text)
        other_layout.addWidget(self.auto_start)
        other_layout.addWidget(self.auto_update)
        other_group.setLayout(other_layout)
        
        # 按钮
        btn_layout = QHBoxLayout()
        self.save_btn = QPushButton("保存")
        self.cancel_btn = QPushButton("取消")
        
        self.save_btn.clicked.connect(self.save_settings)
        self.cancel_btn.clicked.connect(self.close)
        
        btn_layout.addStretch()
        btn_layout.addWidget(self.save_btn)
        btn_layout.addWidget(self.cancel_btn)
        
        layout.addWidget(hotkey_group)
        layout.addWidget(storage_group)
        layout.addWidget(other_group)
        layout.addLayout(btn_layout)
        
        self.setLayout(layout)
    
    def browse_storage_path(self):
        path = QFileDialog.getExistingDirectory(self, "选择保存路径")
        if path:
            self.storage_path.setText(path)
    
    def load_settings(self):
        settings = QSettings("MiaoXing", "Cutnet")
        
        self.screenshot_hotkey.setText(settings.value("hotkeys/screenshot", "PrtScn"))
        self.recording_hotkey.setText(settings.value("hotkeys/recording", "Ctrl+R"))
        self.stop_recording_hotkey.setText(settings.value("hotkeys/stop_recording", "Ctrl+Alt+S"))
        
        default_path = os.path.join(os.path.expanduser("~"), "Desktop")
        self.storage_path.setText(settings.value("storage/path", default_path))
        
        self.watermark_text.setText(settings.value("watermark/text", "©喵星宇宙"))
        self.auto_start.setChecked(settings.value("other/auto_start", False, type=bool))
        self.auto_update.setChecked(settings.value("other/auto_update", True, type=bool))
    
    def save_settings(self):
        settings = QSettings("MiaoXing", "Cutnet")
        
        settings.setValue("hotkeys/screenshot", self.screenshot_hotkey.text())
        settings.setValue("hotkeys/recording", self.recording_hotkey.text())
        settings.setValue("hotkeys/stop_recording", self.stop_recording_hotkey.text())
        
        settings.setValue("storage/path", self.storage_path.text())
        settings.setValue("watermark/text", self.watermark_text.text())
        settings.setValue("other/auto_start", self.auto_start.isChecked())
        settings.setValue("other/auto_update", self.auto_update.isChecked())
        
        QMessageBox.information(self, "提示", "设置已保存！")
        self.close()

class CutnetApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Cutnet - 喵星科创")
        self.setWindowIcon(QIcon("icon.ico"))
        self.setMinimumSize(800, 600)
        
        # 初始化设置
        self.settings = QSettings("MiaoXing", "Cutnet")
        self.recorder = ScreenRecorder()
        self.recorder.finished.connect(self.on_recording_finished)
        
        # 创建系统托盘图标
        self.create_tray_icon()
        
        self.initUI()
        self.setup_hotkeys()
        
    def initUI(self):
        # 主窗口样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #252525;
                color: #ffffff;
                font-family: 'Microsoft YaHei';
            }
            QPushButton {
                background-color: #3d3d3d;
                border: none;
                border-radius: 5px;
                padding: 10px;
                color: #ffffff;
            }
            QPushButton:hover {
                background-color: #4d4d4d;
            }
            QPushButton:pressed {
                background-color: #2d2d2d;
            }
            QScrollArea {
                border: none;
                background-color: #2d2d2d;
            }
            QLabel {
                color: #ffffff;
            }
        """)
        
        # 主布局
        main_widget = QWidget()
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        
        # 顶部工具栏
        toolbar = QWidget()
        toolbar_layout = QHBoxLayout()
        toolbar.setLayout(toolbar_layout)
        
        # 截图按钮（图片按钮）
        self.screenshot_btn = QPushButton()
        self.screenshot_btn.setIcon(QIcon("screenshot.png"))
        self.screenshot_btn.setIconSize(QSize(64, 64))
        self.screenshot_btn.setToolTip("截图 (PrtScn)")
        self.screenshot_btn.clicked.connect(self.start_screenshot)
        
        # 录屏按钮（图片按钮）
        self.recording_btn = QPushButton()
        self.recording_btn.setIcon(QIcon("recording.png"))
        self.recording_btn.setIconSize(QSize(64, 64))
        self.recording_btn.setToolTip("开始录屏 (Ctrl+R)")
        self.recording_btn.clicked.connect(self.toggle_recording)
        
        # 设置按钮（图片按钮）
        self.settings_btn = QPushButton()
        self.settings_btn.setIcon(QIcon("settings.png"))
        self.settings_btn.setIconSize(QSize(64, 64))
        self.settings_btn.setToolTip("设置")
        self.settings_btn.clicked.connect(self.open_settings)
        
        # 添加按钮到工具栏
        toolbar_layout.addWidget(self.screenshot_btn, 3)
        toolbar_layout.addWidget(self.recording_btn, 1)
        toolbar_layout.addWidget(self.settings_btn, 1)
        
        # 文件列表区域
        self.file_list = QScrollArea()
        self.file_list.setWidgetResizable(True)
        
        self.file_content = QWidget()
        self.file_layout = QVBoxLayout()
        self.file_content.setLayout(self.file_layout)
        
        self.file_list.setWidget(self.file_content)
        
        # 底部版权信息
        footer = QLabel()
        footer.setText('<a href="https://miaoxing.com">© 2025 喵星宇宙 版权所有</a>')
        footer.setOpenExternalLinks(True)
        footer.setAlignment(Qt.AlignCenter)
        footer.setStyleSheet("color: #888888;")
        
        # 添加到主布局
        main_layout.addWidget(toolbar)
        main_layout.addWidget(self.file_list, 1)
        main_layout.addWidget(footer)
        
        # 加载示例文件
        self.load_sample_files()
    
    def create_tray_icon(self):
        # 创建系统托盘图标
        image = PILImage.open("icon.ico")
        menu = (
            item('打开', lambda: self.show()),
            item('退出', lambda: QApplication.quit())
        )
        self.tray = pystray.Icon("Cutnet", image, "Cutnet", menu)
        
        # 在单独的线程中运行系统托盘
        threading.Thread(target=self.tray.run, daemon=True).start()
    
    def setup_hotkeys(self):
        # 设置快捷键
        screenshot_hotkey = self.settings.value("hotkeys/screenshot", "PrtScn")
        recording_hotkey = self.settings.value("hotkeys/recording", "Ctrl+R")
        stop_recording_hotkey = self.settings.value("hotkeys/stop_recording", "Ctrl+Alt+S")
        
        try:
            keyboard.add_hotkey(screenshot_hotkey, self.start_screenshot)
            keyboard.add_hotkey(recording_hotkey, self.toggle_recording)
            keyboard.add_hotkey(stop_recording_hotkey, self.stop_recording)
        except Exception as e:
            print(f"设置快捷键失败: {e}")
    
    def start_screenshot(self):
        # 最小化窗口
        self.showMinimized()
        
        # 延迟截图，确保窗口最小化
        QApplication.processEvents()
        QTimer.singleShot(300, self.take_screenshot)
    
    def take_screenshot(self):
        # 获取屏幕截图
        img = ImageGrab.grab()
        
        # 添加水印
        watermark_text = self.settings.value("watermark/text", "©喵星宇宙")
        if watermark_text:
            draw = ImageDraw.Draw(img)
            font = ImageFont.truetype("arial.ttf", 24)
            text_width, text_height = draw.textsize(watermark_text, font=font)
            margin = 20
            position = (img.width - text_width - margin, img.height - text_height - margin)
            draw.text(position, watermark_text, font=font, fill=(255, 255, 255, 128))
        
        # 保存截图
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        default_path = self.settings.value("storage/path", os.path.join(os.path.expanduser("~"), "Desktop"))
        filename = os.path.join(default_path, f"screenshot_{timestamp}.png")
        
        img.save(filename)
        
        # 显示截图完成提示
        self.showNormal()
        QMessageBox.information(self, "提示", f"截图已保存到:\n{filename}")
        
        # 添加到文件列表
        self.add_file_to_list(filename, "screenshot.png")
    
    def toggle_recording(self):
        if self.recorder.isRunning():
            self.stop_recording()
        else:
            self.start_recording()
    
    def start_recording(self):
        if not self.recorder.isRunning():
            storage_path = self.settings.value("storage/path", os.path.join(os.path.expanduser("~"), "Desktop"))
            self.recorder.output_path = storage_path
            self.recorder.start()
            
            self.recording_btn.setIcon(QIcon("recording_active.png"))
            self.recording_btn.setToolTip("正在录屏 (Ctrl+Alt+S停止)")
            
            QMessageBox.information(self, "提示", "录屏已开始，按Ctrl+Alt+S停止")
    
    def stop_recording(self):
        if self.recorder.isRunning():
            self.recorder.recording = False
            self.recorder.wait()
            
            self.recording_btn.setIcon(QIcon("recording.png"))
            self.recording_btn.setToolTip("开始录屏 (Ctrl+R)")
    
    def on_recording_finished(self, filename):
        QMessageBox.information(self, "提示", f"录屏已保存到:\n{filename}")
        self.add_file_to_list(filename, "video.png")
    
    def open_settings(self):
        dialog = SettingsDialog(self)
        dialog.exec_()
        
        # 重新设置快捷键
        keyboard.unhook_all()
        self.setup_hotkeys()
    
    def load_sample_files(self):
        # 清空文件列表
        for i in reversed(range(self.file_layout.count())): 
            self.file_layout.itemAt(i).widget().setParent(None)
        
        # 添加示例文件
        default_path = self.settings.value("storage/path", os.path.join(os.path.expanduser("~"), "Desktop"))
        
        # 查找最近的文件
        try:
            files = []
            for f in os.listdir(default_path):
                if f.startswith(("screenshot_", "recording_")) and f.endswith((".png", ".avi")):
                    files.append((os.path.join(default_path, f), os.path.getmtime(os.path.join(default_path, f))))
            
            # 按时间排序
            files.sort(key=lambda x: x[1], reverse=True)
            
            # 添加前10个文件
            for file_path, _ in files[:10]:
                if file_path.endswith(".png"):
                    self.add_file_to_list(file_path, "screenshot.png")
                elif file_path.endswith(".avi"):
                    self.add_file_to_list(file_path, "video.png")
        except Exception as e:
            print(f"加载文件列表失败: {e}")
    
    def add_file_to_list(self, file_path, icon_name):
        file_item = QWidget()
        file_item.setStyleSheet("""
            QWidget {
                background-color: #3d3d3d;
                border-radius: 5px;
                padding: 5px;
            }
            QWidget:hover {
                background-color: #4d4d4d;
            }
        """)
        
        item_layout = QHBoxLayout()
        
        # 文件图标
        icon_label = QLabel()
        icon_pixmap = QPixmap(icon_name).scaled(32, 32, Qt.KeepAspectRatio)
        icon_label.setPixmap(icon_pixmap)
        
        # 文件名
        file_name = os.path.basename(file_path)
        name_label = QLabel(file_name)
        name_label.setStyleSheet("font-size: 12px;")
        
        # 文件路径
        path_label = QLabel(file_path)
        path_label.setStyleSheet("font-size: 10px; color: #888888;")
        
        # 添加到布局
        item_layout.addWidget(icon_label)
        item_layout.addWidget(name_label, 1)
        
        file_item.setLayout(item_layout)
        
        # 点击打开文件
        def open_file():
            os.startfile(file_path)
        
        file_item.mousePressEvent = lambda e: open_file()
        
        self.file_layout.insertWidget(0, file_item)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle("Fusion")
    app.setFont(QFont("Microsoft YaHei", 10))
    
    # 创建并显示主窗口
    window = CutnetApp()
    window.show()
    
    sys.exit(app.exec_())
